//
//  HMPlayingViewController.m
//  MymusicPlayer
//
//  Created by 陈尚飞 on 15/11/27.
//  Copyright © 2015年 陈尚飞. All rights reserved.
//

#import "HMPlayingViewController.h"
#import "UIView+AdjustFrame.h"
#import "HMMusicModel.h"
#import "HMMusicTool.h"
#import "HMAudioTool.h"
#import "HMLrcView.h"

@interface HMPlayingViewController ()<AVAudioPlayerDelegate>
/// 记录正在播放的音乐
@property (nonatomic,strong) HMMusicModel *playingMusic;

/// 进度的定时器
@property (nonatomic,strong) NSTimer *progressTimer;

/// <#Description#>
@property (nonatomic,strong) AVAudioPlayer *player;

/// 音乐的label
@property (weak, nonatomic) IBOutlet UILabel *songLabel;

/// 歌手的label
@property (weak, nonatomic) IBOutlet UILabel *singerLabel;

/// 歌手的封面
@property (weak, nonatomic) IBOutlet UIImageView *singerIcon;
/// 显示时间总时长
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;

/// 拖拽按钮
@property (weak, nonatomic) IBOutlet UIButton *sliderButton;
/// 拖拽左边的间距
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *silderLeftContraint;

/// 显示时间的label
@property (weak, nonatomic) IBOutlet UILabel *showTimeLabel;
/// 暂停或播放按钮
@property (weak, nonatomic) IBOutlet UIButton *playVsPauseButton;

@property (weak, nonatomic) IBOutlet HMLrcView *LrcView;
@end

@implementation HMPlayingViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.showTimeLabel.layer.cornerRadius = 5.0;
    self.showTimeLabel.layer.masksToBounds = YES;
//    self.showTimeLabel.clipsToBounds = YES;
}
-(void)show {
//  0.判断播放的音乐是否发生变化
    if (self.playingMusic && self.playingMusic != [HMMusicTool playingMusic]) {
    
        [self stopPlayingMusic];
    }
    
    //1.拿到window
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    window.userInteractionEnabled = NO;
    
    //2.设置window的frame
    self.view.frame = window.bounds;
    
    //3.将自身的View添加到window上
    [window addSubview:self.view];
    
    //4.给self.view 添加东湖
    self.view.y = self.view.height;
    
    [UIView animateWithDuration:1.0 animations:^{
        self.view.y = 0;
    } completion:^(BOOL finished) {
        window.userInteractionEnabled = YES;
        
        /// 开始播放音乐
        [self startPlayingMusic];
        
    }];
}

/// 退出控制器
- (IBAction)exit {
    //1.拿到window
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    window.userInteractionEnabled = NO;
    
    [UIView animateWithDuration:1.0 animations:^{
        self.view.y = self.view.height;
    } completion:^(BOOL finished) {
        window.userInteractionEnabled = YES;
        
        //移除定时器
        [self removeProgressTimer];
    }];
    
}

#pragma mark - 对进度条的设置
/// 点击进度条时更新
- (IBAction)tapProgressBackground:(UITapGestureRecognizer *)sender {
    //1.获取用户点击的位置
    CGPoint point = [sender locationInView:sender.view];
    
    //2.改变sliderButton的约束
    if (point.x <= self.sliderButton.width * 0.5) {
        self.silderLeftContraint.constant = 0;
    } else if (point.x >= self.view.width - self.sliderButton.width){
        self.silderLeftContraint.constant = self.view.width -self.sliderButton.width - 1;
    } else {
        self.silderLeftContraint.constant = point.x - self.sliderButton.width * 0.5;
    }
    //3.改变当前播放的时间
    CGFloat progressRation = self.silderLeftContraint.constant / (self.view.width - self.sliderButton.width);
    
    CGFloat currentTime = progressRation * self.player.duration;
    self.player.currentTime = currentTime;
    //4.更新文字
    [self updateInfo];
    
}
/// 拖拽滑块按钮时更新
- (IBAction)panSliderButton:(UIPanGestureRecognizer *)sender {
    
    //1.获取用户拖拽位移
    CGPoint point = [sender translationInView:sender.view];
    [sender setTranslation:CGPointZero inView:sender.view];
    
    //2.改变slierButton的约束
    if (self.silderLeftContraint.constant + point.x <= 0) {
        self.silderLeftContraint.constant = 0;
    }else if(self.silderLeftContraint.constant + point.x >= self.view.width - self.sliderButton.width) {
        self.silderLeftContraint.constant = self.view.width - self.sliderButton.width - 1;
    }else {
        self.silderLeftContraint.constant += point.x;
    }
    
    //3.获取拖拽进度对应的播放时间
    CGFloat progressRation = self.silderLeftContraint.constant / (self.view.width - self.sliderButton.width);
    
    CGFloat currentTime = progressRation * self.player.duration;
    
    //4.更新文字
    NSString *currentTimeStr = [self stringWithTime:currentTime];
    [self.sliderButton setTitle:currentTimeStr forState:UIControlStateNormal];
    [self.showTimeLabel setText:currentTimeStr];
    //5.监听拖拽手势状态
    if (sender.state == UIGestureRecognizerStateBegan) {
        
        //移除定时器
        [self removeProgressTimer];
        //让显示时间的label显示
        
        self.showTimeLabel.hidden = NO;
    }else if (sender.state == UIGestureRecognizerStateEnded) {
        //更新定时器播放时间
        self.player.currentTime = currentTime;
        //添加定时器
        [self addProgressTimer];
        //让显示时间的label隐藏
        self.showTimeLabel.hidden = YES;
    }
    
}
#pragma mark -对播放器控制的方法
/// 开始和暂停的按钮点击
- (IBAction)playVsPauseButtonClick {
    
    self.playVsPauseButton.selected = !self.playVsPauseButton.selected;
    if(self.player.playing) {
    
        [self.player pause];
        [self removeProgressTimer];
    }else {
        [self.player play];
        
        [self addProgressTimer];
    
    }
    
}

/// 下一曲按钮的点击事件
- (IBAction)nextButtonClick {
    [self stopPlayingMusic];
    [HMMusicTool nextMusic];
    [self startPlayingMusic];
    
    
}

/// 上一曲按钮的点击事件
- (IBAction)previousButtonClick {
    [self stopPlayingMusic];
    [HMMusicTool previousMusic];
    [self startPlayingMusic];
    
    
}
/// 歌词或者图片按钮的点击
- (IBAction)lrcOrPicButtonClick:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    
    self.LrcView.hidden = !self.LrcView.hidden;
    
    
}


#pragma mark - 对音乐播放的控制
/// 开始播放音乐
-(void) startPlayingMusic {

    //1.拿到正在播放的音乐
    HMMusicModel *playingMusic = [HMMusicTool playingMusic];
    
    //2.设置界面数据
    if (playingMusic == self.playingMusic) {
        
        [self addProgressTimer];
        return;
    }
    self.playingMusic = playingMusic;
    self.songLabel.text = playingMusic.name;
    self.singerLabel.text = playingMusic.singer;
    self.singerIcon.image = [UIImage imageNamed: playingMusic.icon];

    //3.播放音乐
    self.player = [HMAudioTool playMusicWithName:playingMusic.filename];
    self.totalTimeLabel.text = [self stringWithTime:self.player.duration];
    self.player.delegate = self;
    //4.添加定时器
    [self addProgressTimer];
    [self updateInfo];
    
    //5.改变按钮的状态
    self.playVsPauseButton.selected = NO;
}
/// 停止播放音乐
- (void)stopPlayingMusic {
    //1.清除界面数据
    self.songLabel.text = nil;
    self.singerLabel.text = nil;
    self.singerIcon.image = [UIImage imageNamed:@"play_cover_pic_bg"];
    self.totalTimeLabel.text = nil;
    //2.停止音乐
    [HMAudioTool stopMusicWithName:self.playingMusic.filename];

    //3.移除定时器
    [self removeProgressTimer];
}
#pragma mark - 对控制器的操作

//添加定时器
- (void)addProgressTimer {
    self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateInfo) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.progressTimer forMode:NSRunLoopCommonModes];

}
//移除定时器
- (void)removeProgressTimer {

    [self.progressTimer invalidate];
    self.progressTimer = nil;

}
#pragma mark - AVAudioPlayerDelegate的代理方法

/// 当音乐播放完是调用
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    if (flag) {
        [self nextButtonClick];
    }
}

/// 当音乐打断开始时调用
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
    [self playVsPauseButtonClick];
}

/// 当音乐打断结束时调用
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player {

    [self playVsPauseButtonClick];
}

#pragma mark- 私有方法

- (NSString *)stringWithTime:(NSTimeInterval)time {

    NSInteger minute = time / 60;
    NSInteger second = (NSInteger)time % 60;
    return [NSString stringWithFormat:@"%02ld:%02ld",minute,second];
}
- (void)updateInfo {
    //1.计算播放比例
    CGFloat progressRatio = self.player.currentTime / self.player.duration;
    
    //2.更新滑块的文字
    self.silderLeftContraint.constant = progressRatio * (self.view.width - self.sliderButton.width);
    
    //3.更新滑块的文字
    
    NSString *currentTimeStr = [self stringWithTime:self.player.currentTime];
    [self.sliderButton setTitle:currentTimeStr forState:UIControlStateNormal];
    //[self.showTimeLabel setText:currentTimeStr];
}

@end
